<template>
  <div>
    <div style="margin: 10px 0;">
      <el-input placeholder="请输入名称查询" v-model="name" clearable style="width: 200px"></el-input>
      <el-button type="primary" icon="el-icon-search" style="margin-left: 5px" @click="search">查询</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" @selection-change="handleSelectionChange" style="width: 100%"
              :header-cell-style="{background:'#e7e8ef',color:'#4f5257'}"
              stripe fixed border>
      <el-table-column
          prop="id"
          type="selection"
          width="40">
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名称">
      </el-table-column>
      <el-table-column prop="goodsImg" label="商品图片" width="120">
        <template slot-scope="scope">
          <div>
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.goodsImg"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="商品价格（元）" ></el-table-column>
      <el-table-column prop="num" label="购买数量" >
        <template v-slot="scope">
          <el-input-number v-model="scope.row.num"  :min="1" :max="100" @change="num(scope.row)" label="描述文字"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
          label="删除"
          width="90">
        <template slot-scope="scope">
          <el-popconfirm
              style="margin-left: 5px"
              confirm-button-text='确定'
              cancel-button-text='取消'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handleDelete(scope.$index, scope.row)">
            <el-button type="danger" size="mini"   slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <div style="text-align: center;">
      <div style="padding: 10px 0">总价：<span style="color: #ff405d;font-size: 18px">￥{{ sumPrice }}</span></div>
      <el-button size="big" style="color: white;background-color: orangered" @click="settle">立 刻 结 算</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "Cart",
  data(){
    return{
      name: "",
      tableData:[],
      currentPage: 4,
      pageNum:0,
      pageSize:5,
      total:0,
      dialogVisible: false,
      form: {},
      ids:[],
      multipleSelection: [],
      roles: [],
      sumPrice: 0
    }
  },
  created() {
    this.load()
  },
  methods:{
    //结算
    settle(){
      if (!this.multipleSelection || !this.multipleSelection.length){
        this.$message.warning("请选择需要购买的商品！")
        return
      }
      let data = {name: this.multipleSelection[0].goodsName,sumPrice: this.sumPrice,carts: this.multipleSelection}
      this.request.post("/orders",data).then(res =>{
        if (res.code === 200){
          this.$message.success("成功")
          this.load()
        }else {
          this.$message.error(res.message)
        }
      })
    },
    //数量更改
    num(row){
      this.request.post("/carts/updateNum/"+row.id+"/"+row.num).then(res =>{
        // this.load()
        //计算总价
        this.sumPrice = 0
        this.multipleSelection.forEach(item =>{
          item.num = row.num //更新选中的数组数量
          this.sumPrice +=item.price * row.num //加上选择的数据
        })
        this.sumPrice=this.sumPrice.toFixed(2)//取得两位小数
      })
    },
    search(){
      if (this.name!=''||this.name!=null){
        this.load()
        this.$message({
          message: '查询成功',
          type: 'success'
        });
      }else{
        this.$message({
          message: '请输入查询内容',
          type: 'warning'
        });
      }
    },
    load(){
      this.request.get("/carts/page",{
            params:{
              pageNum:this.pageNum,
              pageSize:this.pageSize,
              name:this.name
            }
          }
      ).then(res =>{
        if(res.code === 200){
          this.tableData=res.data.records
          this.total=res.data.total
        }else {
          this.$message.error(res.message)
        }
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    handleDelete(index, row) {
      this.request.delete("/carts/"+(index,row).id).then(res=>{
        if (res.code===200){
          this.load()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      })
    },
    delBatch(){
      let ids = this.multipleSelection.map(v =>v.id)
      if (ids.length!=0){
        this.$confirm('你正在进行批量删除操作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.request.post("/carts/batch/", ids).then(res => {
            if (res.code===200){
              this.load()
              this.$message({
                type: 'success',
                message: '批量删除成功!'
              });
            }else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }else {
        this.$message.warning("请选择删除记录")
      }
    },
    /**
     * 选择框
     * */
    handleSelectionChange(val) {
      this.sumPrice=0
      this.multipleSelection = val;
      if (val && val.length){
        val.forEach(item =>{
          this.sumPrice +=item.num * item.price
        })
        this.sumPrice=this.sumPrice.toFixed(2)
      }
    },
    /**
     * 自定义操作列
     * @param index
     * @param row
     */
    handleSizeChange(val) {
      this.pageSize = val;
      this.load()
    },
    handleCurrentChange(val) {
      this.pageNum=val
      this.load()
    },
    handleAvatarSuccess(res){
      this.form.img=res
    },
  }
}
</script>

<style scoped>

</style>